﻿using System.Collections.Generic;
using System.Linq;
using Test.DataAccess.POCO;
using Test.Site.Data.Models;

namespace Test.Site.Data.Helper
{
    public class MenuHelper
    {
        /// <summary>
        /// 根据权限生成菜单
        /// </summary>
        public static List<MenuItem> BuildAdminMenu(IEnumerable<Permission> allPermissions)
        {
            allPermissions = allPermissions.ToList();
            var menuPermission = allPermissions
                    .Where(p => p.IsMenu &&/* p.Area == "Admin" &&*/ (p.Parent_Id == null || p.Parent_Id == ""))
                    .ToList();

            return GetSubMenu(menuPermission, allPermissions);
        }

        private static List<MenuItem> GetSubMenu(IEnumerable<Permission> permissions, IEnumerable<Permission> allPermissions)
        {
            var result = new List<MenuItem>();
            foreach (var permission in permissions.OrderBy(p => p.Order))
            {
                var menuTmp = new MenuItem()
                {
                    Url = permission.Url,
                    Controller = permission.Controller,
                    Action = permission.Action,
                    MenuItemName = permission.PermissionName,
                    ChildrensMenuItem = GetSubMenu(permission.Chindren.Where(p => allPermissions.Count(ap => ap.Id == p.Id) > 0), allPermissions),
                    CssClass = permission.CssClass
                };
                result.Add(menuTmp);
            }
            return result;
        }
    }
}
